package com.huafv.flyauth.security;

import com.huafv.flyauth.core.domain.Result;
import com.huafv.flyauth.core.redis.RedisCache;
import com.huafv.flyauth.utils.JwtUtil;
import com.huafv.flyauth.web.admin.entity.SysUser;
import com.huafv.flyauth.web.admin.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private SysUserService sysUserService;


    @Override
    public Result login(SysUser user) {

        // 通过 UsernamePasswordAuthenticationToken 获取用户名和密码
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword());

        // AuthenticationManager 委托机制对 authenticationToken 进行用户认证
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);

        //如果认证没有通过，给出对应的提示
        if (Objects.isNull(authenticate)) {
            throw new RuntimeException("登录失败");
        }

        // 如果认证通过，使用 user 生成jwt jwt 存入 Result 返回

        // 如果认证通过，拿到这个当前登录用户信息
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();

        //获取当前用户的userid
        String username = loginUser.getSysUser().getUsername();

        // secret
        String secret = "huafv";
        // expireDate
        Date nowDate = new Date();
        Date expireDate = new Date(nowDate.getTime() + 1000 * 7);
        // data
        Map<String, Object> map = new HashMap<>();
        map.put("sub", "fly");
        map.put("user", username);

        String token = JwtUtil.createToken(secret, map, expireDate);

        //把完整的用户信息存入redis  userid为key   用户信息为value
        redisCache.setCacheObject("login:" + username, loginUser);

        Map<String, Object> data = new HashMap<>();
        data.put("token", token);

        SysUser sysUser = sysUserService.getByUsername(user.getUsername());
        sysUser.setPassword(null);

        data.put("user", sysUser);

        return Result.success(data);
    }

    @Override
    public boolean logout() {

        //从 SecurityContextHolder 中 的 username
        UsernamePasswordAuthenticationToken authentication =
                (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();

        LoginUser loginUser = (LoginUser) authentication.getPrincipal();

        System.out.println("Logout:");
        System.out.println(loginUser);

        String username = loginUser.getSysUser().getUsername();

        //根据userid找到redis对应值进行删除
        redisCache.deleteObject("login:" + username);

        return true;
    }

}